import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState, AppThunk } from '@/store';
import * as api from '@/api/app';

export interface AppState {
    fetching: boolean;
}

const initialState: AppState = {
    fetching: false,
};

export const projectsSlice = createSlice({
    name: 'projects',
    initialState,
    reducers: {
        getApp(state) {
            state.fetching = true;
        },
        getAppSuccess(state, action: PayloadAction<number>) {
            state.fetching = false;
        },
        getAppFailed(state, action: PayloadAction<any>) {
            state.fetching = false;
        },
    },
});

export const { getApp, getAppSuccess, getAppFailed } = projectsSlice.actions;

export const getAppAsync =
    (query: any): AppThunk =>
    async (dispatch, getState) => {
        const state: RootState = getState();

        try {
            dispatch(getApp());
            const res = await api.fetchApp();
            dispatch(getAppSuccess(1));
        } catch (error) {
            dispatch(getAppFailed({ error }));
        }
    };

export default projectsSlice.reducer;
